<template>
  <NModal
    :show="show"
    @update:show="$emit('update:show', $event)"
  >
    <div class="custom-modal included-modal">
      <div class="modal-title">
        <span>关联未入藏藏品</span>
        <img
          src="@/assets/images/meeting_dialog_close.png"
          alt=""
          @click="$emit('update:show', false)"
        />
      </div>
      <div class="modal-container included-container">
        <div class="menuStyle">
          <div style="width: 45%; margin-right: 1rem">
            <div :style="type != 2 && type != 3 ? 'height: 40vh' : 'height: 50vh'">
              <TableView class="table">
                <template #form>
                  <NSpace>
                    <NSelect
                      :value="form.compony"
                      @update:value="handleUpdateCompony"
                      filterable
                      placeholder=""
                      :options="codeOptions"
                      style="width: 180px; margin-right: 10px"
                    />
                    <n-form
                      ref="formSearchRef"
                      :modal="form"
                      :rules="numberRule"
                    >
                      <NFormItem
                        :show-label="false"
                        path="yesNO"
                      >
                        <NInput
                          v-model:value="form.yesNO"
                          :show-button="false"
                        />
                      </NFormItem>
                    </n-form>
                    <NButton
                      type="primary"
                      style="width: 78px; margin-right: 10rem"
                      ghost
                      @click="queryTableData(true)"
                    >
                      查询
                    </NButton>
                    <!-- <NButton
          type="primary"
          style="width: 100rem; margin-bottom: 10rem"
          @click="addGroupOpenFn"
        >
          新增
        </NButton> -->
                  </NSpace>
                </template>
                <div class="topTitle">版本库</div>

                <template #table="$props">
                  <n-tabs
                    type="card"
                    v-model:value="curSourceType"
                    @update:value="handleChangeSourceType"
                  >
                    <n-tab-pane
                      :name="item.value"
                      :tab="item.label"
                      v-for="item in sourceTypeList"
                    >
                      <NDataTable
                        :bordered="false"
                        :columns="columns"
                        :data="tableData"
                        :max-height="type == 2 || type == 3 ? 300 : 120"
                        :min-height="type == 2 || type == 3 ? 300 : 120"
                        :loading="tableLoading"
                      />
                    </n-tab-pane>
                  </n-tabs>
                </template>

                <template #pagination>
                  <NPagination
                    show-size-picker
                    show-quick-jumper
                    :page-sizes="paginationReactive.pageSizes"
                    :item-count="paginationReactive.itemCount"
                    :page="paginationReactive.page"
                    :page-size="paginationReactive.pageSize"
                    @update:page="paginationReactive.onChange"
                    @update:page-size="paginationReactive.onUpdatePageSize"
                    :suffix="() => '页'"
                  >
                    <template #prefix>
                      <span style="font-size: 14px">共{{ paginationReactive.itemCount }}条</span>
                    </template>
                  </NPagination>
                </template>
              </TableView>
            </div>
            <!-- <NScrollbar :style="type != 2 && type != 3 ? 'height: 40vh' : 'height: 30vh'">
              <div class="ac-title">批次信息</div>
              <InfoBatchCatalog
                :id="$route.query.batchCode!"
                @backData="backData"
                :type-show="type"
                :code="id"
              />
              <div
                class="ac-title"
                v-if="type != 2 && type != 3"
              >
                物品信息
              </div>
              <InfoGoods
                :id="id"
                :subItemCode="$route.query.subItemCode"
                :type-show="type"
                :code="id"
                v-if="type != 2 && type != 3"
              />
            </NScrollbar> -->
          </div>
          <NScrollbar style="width: 55%; height: 100%">
            <div>
              <div class="dynamic-form-demo">
                <DynamicFormComponent
                  ref="dfInst"
                  v-if="formData.BMCOM003 && !jsonInfoLoading"
                  :data="formData"
                  :createVars="createVars"
                  :onlyTable="isHistory"
                  :disabledKeys="['BMCOM008']"
                />
              </div>
              <!-- 
            :listData ='responData', -->
              <!-- <DynamicPageForm
            ref="baseFormRef"
            :form-model="otherJson"
            :model="formData"
            :form-data="formData"
            label-placement="left"
            require-mark-placement="left"
            :label-width="140"
            @update:value="handleUpdateFormData"
            class="ac-card"
          /> -->
              <n-form
                :modal="form"
                :rules="numberRule"
                style="margin-left: 45px"
              >
                <NFormItem
                  label="附件:"
                  path="fileIds"
                >
                  <FUploader
                    :fileList="fileList"
                    @update:fileList="handleUploadList"
                    style="width: 250px"
                  />
                </NFormItem>
              </n-form>
              <FixedAction>
                <NSpace justify="center">
                  <NButton
                    style="width: 78px"
                    ghost
                    @click="goBack"
                  >
                    取消
                  </NButton>
                  <NButton
                    type="primary"
                    style="width: 78px"
                    @click="submit"
                    :loading="loading"
                  >
                    保存
                  </NButton>
                  <NButton
                    type="primary"
                    style="width: 108px"
                    @click="submitAndReview"
                    :loading="loadingReview"
                    v-if="type == 1 || type == 2 || type == 3"
                  >
                    提交审核
                  </NButton>
                </NSpace>
              </FixedAction>
            </div>

            <NModal
              :auto-focus="false"
              v-model:show="modalVisible"
            >
              <VDialogContent
                @close="modalVisible = false"
                @submit="addGroupFn"
                title="套组"
              >
                <NForm
                  :model="form"
                  :rules="formRules"
                  ref="groupFormRef"
                  label-placement="left"
                  require-mark-placement="left"
                  label-width="80"
                >
                  <NFormItem
                    label="套组名称"
                    path="GroupName"
                  >
                    <NInput
                      v-model:value="form.GroupName"
                      class="inputGroup"
                      @input="inputGroupName"
                    />
                  </NFormItem>
                </NForm>
              </VDialogContent>
            </NModal>
          </NScrollbar>
        </div>
        <div class="container-bottom">
          <div class="btn-list">
            <n-button @click="handleCancel">取消</n-button>
            <n-button
              type="primary"
              @click="handleSubmit"
            >
              确定
            </n-button>
          </div>
        </div>
      </div>
    </div>
  </NModal>
</template>

<script setup lang="ts">
import { ref, watch, reactive, h, shallowRef, toRaw, onDeactivated } from 'vue'
import {
  NSpace,
  NButton,
  NForm,
  NFormItem,
  NInput,
  NSelect,
  type FormRules,
  useMessage,
  NDataTable,
  NModal,
  NScrollbar,
  type FormInst,
  type DataTableColumns,
  NPagination,
  NTabs,
  NTabPane,
  NEllipsis
} from 'naive-ui'
import { useRoute } from 'vue-router'
import TableView from '@/components/TableView.vue'
import { sendRequest } from '@/utils/api'
import VDialogContent from '@/views/OA/Common/DialogContent.vue'
import { mergeWith, isArray } from 'lodash-es'
import DynamicPageForm from '@/components/DynamicPageForm/DynamicPageForm.vue'
import type { ModelJson } from '@/components/DynamicPageForm/DynamicFormTypes'
import FixedAction from '@/components/FixedAction.vue'
import InfoGoods from '@/components/CollectProcess/InfoGoods/index.vue'
import InfoBatchCatalog from '@/components/CollectProcess/InfoBatchCatalog/index.vue'
// import VUpload from '@/views/OA/Common/Upload.vue'
import useRouteQuery from '@/hooks/useRouteQuery'
import useRouteReplace from '@/hooks/useRouteReplace'
import useSubmit, {
  defaultVersionTypeValue,
  defaultVersionTypeKey
} from './DynamicFormComponent/useSubmit'
import DynamicFormComponent from './DynamicFormComponent/index.vue'
import FUploader from '@/views/Collection/Collect/Batch/components/FUploader.vue'
import { formatedDataUtil, formatedDataToFormUtil } from './DynamicFormComponent/utils'
import { useViewerStore } from '../../Common/store'

const props = defineProps({
  show: {
    type: Boolean,
    required: true
  }
})

const emit = defineEmits(['update:show', 'select', 'reset', 'cancel', 'submit'])

const useStore = useViewerStore()
const { dfInst, formData, createVars, submitLoading, submit: submitR } = useSubmit()

const handleCancel = () => {
  emit('update:show', false)
  emit('cancel')
}

const handleSubmit = () => {
  emit('update:show', false)
  emit('submit', formData.value)
}

watch(
  formData,
  (v) => {
    console.log('==>', toRaw(v))
    dfInst.value?.formInst?.$forceUpdate()
  },
  { deep: true }
)

const route = useRoute()
const message = useMessage()
const id = ref()
const type = ref()
const subItemCode = ref()
const routeReplace = useRouteReplace(route.query.redirect as string)
const form: any = reactive({
  compony: 0,
  yesNO: null,
  code: null,
  number: null,
  name: null,
  GroupName: null,
  rank: null,
  choice: null,
  itemName: null,
  assetCode: null,
  serialNumber: null,
  shelfNumber: null
})
//筛选条件
const paginationReactive = reactive({
  page: 1,
  pageSize: 10,
  showSizePicker: true,
  pageSizes: [10, 20, 50, 100, 500],
  itemCount: 0,
  onChange: (page: number) => {
    paginationReactive.page = page
    queryTableData()
  },
  onUpdatePageSize: (pageSize: number) => {
    paginationReactive.pageSize = pageSize
    queryTableData(true)
  }
})
const codeOptions = ref([
  { value: 0, label: '全部' },
  { value: 1, label: 'ISBN' },
  { value: 2, label: '题名' },
  { value: 3, label: '馆藏码' }
])
const taozuOption = ref() //套组下拉
const sourceTypeList = ref([
  {
    label: '总馆',
    value: 1
  },
  {
    label: '本馆',
    value: 2
  },
  {
    label: '浙图',
    value: 3
  }
]) // 来源
const curSourceType = ref(1)

const tableLoading = ref()
const tableData: any = ref([])
const columns: DataTableColumns = [
  {
    title: 'ISBN',
    key: 'isbn',
    width: '8rem',
    align: 'center'
  },
  {
    title: '题名',
    key: 'title',
    width: '12rem',
    align: 'center',
    render({ title }) {
      return h(
        NEllipsis,
        { lineClamp: 2 },
        {
          default: () => title,
          tooltip: () => {
            return h('div', { style: 'width: 200px' }, { default: () => title })
          }
        }
      )
    }
  },
  {
    title: '出版者',
    key: 'publisher',
    width: '10rem',
    align: 'center'
  },
  // {
  //   title: '版次印次',
  //   key: 'version',
  //   width: '10rem',
  //   align: 'center'
  // },
  {
    title: '出版时间',
    key: 'publisherTime',
    width: '8rem',
    align: 'center'
  },
  {
    title: '来源',
    key: 'sourceType',
    width: '5rem',
    align: 'center',
    render: (row) => {
      switch (row.sourceType) {
        case 1:
          return '总馆'
        case 2:
          return '本馆'
        case 3:
          return '浙图'
      }
    }
  },
  {
    title: '操作',
    key: 'action',
    width: '5rem',
    align: 'center',
    fixed: 'right',
    render: (e: any) => {
      return h(
        NButton,
        {
          type: 'primary',
          quaternary: true,
          // 历史文献不套编所以禁用
          style: { display: isHistory.value ? 'none' : 'inline' },
          onClick: () => {
            console.log(e)
            doubleCodeFn(e)
          }
        },
        {
          default: () => '套编'
        }
      )
    }
  }
]
const formRules: FormRules = {
  GroupName: {
    required: true,
    trigger: ['blur', 'input'],
    type: 'any',
    validator: (_: any, value: any) => {
      if (!value) return new Error('套组名称不能为空')
      if (value.length > 100) return new Error('套组名称字数不能超过100')
    }
  },
  loginName: {
    required: true,
    trigger: 'blur',
    message: '登录名不能为空'
  },
  assetCode: {
    required: true,
    trigger: ['blur', 'input'],
    renderMessage: () => {
      if (!form.assetCode) return '馆藏码不能为空'
      else if (!/^[0-9]*$/.test(form.assetCode)) return '馆藏码是数字组成'
    },
    validator: () => {
      if (!form.assetCode) return false
      if (!/^[0-9]*$/.test(form.assetCode)) return false
      // if (!form.assetCode||!form.assetCode?.match(/^[0-9]*$/)) return new Error()
    },
    message: '馆藏码不能为空'
  }
}
const clueMethodOptions: any = reactive([])

const formInst = ref<FormInst | null>(null)
const modelJson = ref({} as ModelJson)
const otherJson = ref({} as ModelJson)
const queryJsonBM = async (code: string) => {
  try {
    const [error, res]: any = await sendRequest({
      module: 'collection',
      api: 'jsonContent',
      override: {
        params: {
          name: `BM_${code}.json`
        }
      }
    })
    if (error) throw error
    if (res.code !== 200) throw new Error(res.message)
    otherJson.value = res.data
  } catch (error) {
    console.error(error)
  }
}
// 附件
const handleUploadList = (v: any) => {
  form.fileIds = v.map((e: any) => e.file?.remoteId).join(',')
  fileList.value = v
}
const queryJson = async (code: string) => {
  try {
    const [error, res]: any = await sendRequest({
      module: 'collection',
      api: 'jsonContent',
      override: {
        params: {
          name: `${code}.json`
        }
      }
    })
    if (error) throw error
    if (res.code !== 200) throw new Error(res.message)
    modelJson.value = res.data
  } catch (error) {
    console.error(error)
  }
}
const fileList: any = ref([])
const baseModel: ModelJson = {
  elements: [
    {
      type: 'NInput',
      key: 'itemName',
      label: '名称：',
      rule: {
        required: true,
        message: '名称必填'
      }
    },
    {
      type: 'NDatePicker',
      key: 'receiveTime',
      label: '接收时间：',
      props: { type: 'datetime', format: 'yyyy-MM-dd HH:mm:ss' },
      style: { flex: 1 },
      rule: {
        required: true,
        message: '接收时间必填'
      }
    },
    {
      type: 'NSelect',
      key: 'collectTypeCode',
      label: '征集方式：',
      props: {
        options: clueMethodOptions,
        valueField: 'code',
        labelField: 'name'
      },
      rule: {
        required: true,
        message: '征集方式必填'
      }
    },
    {
      type: 'NInputNumber',
      key: 'itemNum',
      label: '数量：',
      style: { flex: 1 },
      props: {
        showButton: false,
        min: 0
      },
      rule: {
        type: 'number',
        required: true,
        message: '数量必填'
      }
    },
    {
      type: 'NInput',
      key: 'receiveUser',
      label: '接收人：',
      rule: {
        required: true,
        message: '接收人必填'
      }
    },
    {
      type: 'NInput',
      key: 'notes',
      label: '备注：',
      props: {
        type: 'textarea',
        rows: 1
      },
      rule: {
        required: true,
        message: '备注必填'
      }
    }
  ]
}
const model = shallowRef<any>(baseModel)
const setModelJson = async (code?: string | null) => {
  if (!code) return (model.value = toRaw(baseModel))
  model.value = mergeWith({}, toRaw(baseModel), await queryJson(code), (obj: any, src: any) => {
    if (isArray(obj)) return [...obj, ...src]
  }) as ModelJson
}
const clueInfoLoading = ref(false)
const backDataRef = ref()
const backData = (e: any) => {
  backDataRef.value = e
  // solicitMethodCode collector
  if (type.value == 1 || type.value == 2) {
    //编目添加，祥编映射征集方式，藏家
    formData.value['BMCOM001'] = e?.solicitMethodCode
    formData.value['BMCOM002'] = e?.collector
  }
  console.log(e)
}
const GroupList: any = ref([])
const jsonInfoLoading = ref(false)
const getJSONInfo = async (subItemCode: any, data: any) => {
  jsonInfoLoading.value = true
  return sendRequest({
    module: 'collectProcess',
    api: 'commonJsonInfo',
    uri: {
      subItemCode: subItemCode
    }
  })
    .then(async ([err, res]) => {
      if (err) return
      console.log(res, 'ccc')
      //
      if (res.data?.catalogInfo) {
        formData.value = JSON.parse(res.data?.catalogInfo || '{}')
      }
      //编辑 非空 编目 空的
      if (type.value === '3' && !formData.value[defaultVersionTypeKey]) {
        formData.value[defaultVersionTypeKey] = defaultVersionTypeValue
      }
      // else if(type.value === '2') {
      //   formData.value['BMCOM001']=backDataRef.value?.solicitMethodCode
      // formData.value['BMCOM002']=backDataRef.value?.collector
      // }
      else if (route.query?.type == '1' && !res.data?.catalogInfo) {
        formData.value['BMCOM001'] = backDataRef.value?.solicitMethodCode
        formData.value['BMCOM002'] = backDataRef.value?.collector
        checkIsDetail(route.query?.subItemCode)
      }
      if (isHistory.value) {
        formData.value = {
          ...formData.value,
          ...formatedDataToFormUtil.collectingDistrictDataList(data?.collectingDistrictDataList),
          ...formatedDataToFormUtil.collectingResponsibleDataList(
            data?.collectingResponsibleDataList
          )
        }
        if (formData.value.toString() != '{}')
          formData.value['BMCOM008'] = `${formData.value.ZRZ?.[0]?.['BMLSWX012'] || ''}${
            formData.value.ZRZ?.[0]?.['BMLSWX011']
              ? '(' + formData.value.ZRZ?.[0]?.['BMLSWX011'] + ')'
              : ''
          }${formData.value.ZRZ?.[0]?.['BMLSWX013'] || ''}`
      }

      // ts-ignore
    })
    .finally(() => (jsonInfoLoading.value = false))
}

watch(
  () => formData.value.ZRZ?.[0]?.['BMLSWX011'],
  (v) => {
    formData.value['BMCOM008'] = `${formData.value.ZRZ?.[0]?.['BMLSWX012'] || ''}${
      formData.value.ZRZ?.[0]?.['BMLSWX011']
        ? '(' + formData.value.ZRZ?.[0]?.['BMLSWX011'] + ')'
        : ''
    }${formData.value.ZRZ?.[0]?.['BMLSWX013'] || ''}`
  }
)
watch(
  () => formData.value.ZRZ?.[0]?.['BMLSWX012'],
  (v) => {
    formData.value['BMCOM008'] = `${formData.value.ZRZ?.[0]?.['BMLSWX012'] || ''}${
      formData.value.ZRZ?.[0]?.['BMLSWX011']
        ? '(' + formData.value.ZRZ?.[0]?.['BMLSWX011'] + ')'
        : ''
    }${formData.value.ZRZ?.[0]?.['BMLSWX013'] || ''}`
  }
)
watch(
  () => formData.value.ZRZ?.[0]?.['BMLSWX013'],
  (v) => {
    formData.value['BMCOM008'] = `${formData.value.ZRZ?.[0]?.['BMLSWX012'] || ''}${
      formData.value.ZRZ?.[0]?.['BMLSWX011']
        ? '(' + formData.value.ZRZ?.[0]?.['BMLSWX011'] + ')'
        : ''
    }${formData.value.ZRZ?.[0]?.['BMLSWX013'] || ''}`
  }
)
// const isHistory = ref(false)
const responData = ref()
// 当isHistory true获取责任者区，字母区表格数据，
const getRelativeData = async () => {
  const [error, res] = await sendRequest({
    module: 'collectProcess',
    api: 'skipAssociation',
    override: {
      params: {
        type: route.query?.relativeId != '0' && !route.query?.relativeId ? 0 : 1,
        associationId: route.query?.relativeId,
        receiveId: route.query?.id
      }
    }
  })
  if (error) return message.error(error.message)
  if (res.code !== 0) return message.error(res.msg)
  // formatedDataToForm.
}
const checkIsDetail = async (subItemCode: any) => {
  try {
    clueInfoLoading.value = true
    const [error, res] = await sendRequest({
      module: 'collectProcess',
      api: 'commonGoodsInfo',
      uri: {
        subItemCode: subItemCode
      }
    })
    if (error) throw error
    if (res.code !== 0) throw new Error(res.msg)
    const { data } = res
    if (!formData.value['BMCOM003']) formData.value['BMCOM003'] = data.itemTypeCode
    if (!formData.value['BMCOM007']) formData.value['BMCOM007'] = data.itemName

    // if(formData.value['BMCOM007']?.indexOf('T01'))
    // {
    //   isHistory.value =true
    //   // getRelativeData()
    // }
    // else
    // {
    //   isHistory.value = false
    // }
  } catch (error) {
    console.error(error)
  } finally {
    setTimeout(() => {
      clueInfoLoading.value = false
    }, 2000)
  }
}

const getInfo = async (subItemCode: any) => {
  sendRequest({
    module: 'collectProcess',
    api: 'catalogInfo',
    uri: {
      subItemCode: subItemCode
    }
  }).then(async ([err, res]) => {
    if (err) return

    // keysOf(res.data.detailVo).forEach((e) => {
    //   form[e] = res.data[e] as never
    // })
    console.log(res)
    GroupList.value = res.data?.itemsStagingList
    if (type.value === '3' || type.value === '1') {
      fileList.value = res.data?.collectingItems?.fileList?.map((e: any, i: number) => ({
        id: i,
        name: e.name,
        status: 'finished',
        url: e.path,
        file: {
          remoteId: e.id
        }
      }))
    }
    form.assetCode = res.data?.itemsStaging?.assetCode
    form.itemName = res.data?.itemsStaging?.itemName
    form.serialNumber = res.data?.itemsStaging?.serialNumber
    form.shelfNumber = res.data?.itemsStaging?.shelfNumber
    // @ts-ignore
    form.choice = (res.data?.collectSetId || '') + ''
    res.data?.collectSetId && makeLineDetail(res.data?.collectSetId)
    isHistory.value = !res.data?.canTaoBian
    // res.data?.detailVo?.itemTypeCode && queryJsonBM(res.data?.detailVo?.itemTypeCode)
    // formData.value = JSON.parse(res.data?.catalogInfo||{})
    getJSONInfo(subItemCode, res.data)
  })
}
const modalVisible = ref(false)
const queryTableData = async (resetPage = false) => {
  if (!form.yesNO) return message.warning('请先输入筛选条件')
  if (!form.yesNO && !resetPage) {
    // message.info('请先输入筛选条件')
    return
  }
  tableLoading.value = true
  if (resetPage) paginationReactive.page = 1
  const [error, res] = await sendRequest({
    module: 'collectProcess',
    api: 'getCatalogInfo',
    override: {
      params: {
        page: paginationReactive.page,
        limit: paginationReactive.pageSize,
        type: form.compony,
        keyWords: form.yesNO,
        sourceType: curSourceType.value
      }
    }
  })
  if (error) return message.error(error.message)
  tableData.value = res.data.catalogInfoVoList || []
  paginationReactive.itemCount = res.data.totalCount
  tableLoading.value = false
}

/**切换来源tab */
const handleChangeSourceType = () => {
  queryTableData(true)
}
// 套编
const doubleCodeFn = async (e: any) => {
  const [error, res] = await sendRequest({
    module: 'collectProcess',
    api: 'getAssetCodeDetailInfo',
    override: {
      params: {
        type: e.type,
        keyWords: e.sourceType == 2 ? e.subItemCode : e.keywords,
        sourceType: e.sourceType
      }
    }
  })
  if (error) return message.error(error.message)
  let data = res.data
  if (!data) return message.error('没有查询到数据')
  formData.value = Object.assign(JSON.parse(data || '{}'))
}
const getTaozuFn = async () => {
  // 套组下拉接口
  const [error, res] = await sendRequest({
    module: 'collectProcess',
    api: 'getPullMenusCollectSet'
  })
  if (error) return message.error(error.message)

  taozuOption.value = res.data
}
getTaozuFn()
// 新增一条数据
const addGroupOpenFn = () => {
  modalVisible.value = true
}
const groupFormRef = ref()
const addGroupFn = async () => {
  const validate = await Promise.all([
    new Promise((resolve, reject) => {
      groupFormRef.value?.validate((error: any) => {
        if (error) return reject(error)
        resolve(true)
      })
    })
  ])
  if (!validate.every(Boolean)) return
  const [error, res] = await sendRequest({
    module: 'collectProcess',
    api: 'collectSetSave',
    override: {
      data: {
        setName: form?.GroupName
      }
    }
  })
  if (error) return message.error(error.message)
  message.success(res.data)
  modalVisible.value = false
  getTaozuFn()
  form.GroupName = null
}
const numberRule = ref({
  yesNO: {
    required: true,
    trigger: ['blur', 'input'],
    validator: () => /^[0-9-.]+$/.test(form.yesNO),
    message: '只允许数字和字符-'
  }
})
useRouteQuery('id', () => {
  if (route.query.id) {
    // queryJsonBM('T001001')
    if (route.query?.type == '3' || route.query?.type == 1) {
      getInfo(route.query?.subItemCode)
    }

    // queryTableData(true)
  }
})
const isHistory = ref(false)
const keyUpDown = (e: any) => e.key == 'Enter' && ((paginationReactive.page = 1), queryTableData())
onDeactivated(() => window.removeEventListener('keyup', keyUpDown, false))
watch(
  () => route,
  async () => {
    if (route.path == '/OA/DigitalCollation/DigitalCollationAdd') {
      window.addEventListener('keyup', keyUpDown, false) // 回车
      id.value = route.query?.id
      type.value = route.query?.type //区分添加和编目 2 是添加，1 是编目
      subItemCode.value = route.query?.subItemCode
      // isHistory.value = route.query?.isHistory=='true'?true:false
      form.itemName = null
      form.assetCode = null
      form.serialNumber = null
      form.shelfNumber = null
      form.yesNO = null
      if (type.value !== '1') formData.value = { [defaultVersionTypeKey]: defaultVersionTypeValue }
      tableData.value = []
      fileList.value = []
      // queryJsonBM('T001001')

      if (type.value === '3' || type.value === '1') getInfo(route.query?.subItemCode) //编辑 编目
      // queryTableData(true)//版本库默认不查询
      // if(route.query?.type == '1') checkIsDetail(route.query?.subItemCode)//编目

      // 编目页面添加字段默认值，正文语种默认为汉语，出版国代码默认为中国
      formData.value['BMTRA009'] = '汉语'
      formData.value['BMTRA010'] = '中国'
    }
  },
  { deep: true, immediate: true }
)
const formSearchRef: any = ref()
watch(
  () => form.compony,
  async () => {
    console.log(form.compony)
    formSearchRef.value?.restoreValidation()
    numberRule.value = {
      yesNO: {
        required: form.compony == 2 || form.compony == 0 ? false : true,
        trigger: ['blur', 'input'],
        validator: () => {
          return form.compony == 2 || form.compony == 0 ? undefined : /^[0-9-.]+$/.test(form.yesNO)
        },
        restoreValidation: (e) => {
          form.compony == 2 || form.compony == 0 ? this.restoreValidation() : null
        },
        message: '只允许数字和字符-'
      }
    }
  },
  { deep: true, immediate: true }
)
// 返回
const goBack = () => {
  // history.back()
  routeReplace()
}

window.dfInst = dfInst
const baseFormRef = ref<FormInst | null>(null)
const loading = ref()
const loadingReview = ref()
const canReview = ref(false)
const submit = async (noBack?: any) => {
  canReview.value = true
  // const validate = await Promise.all([
  //   // 暂时未使用

  //   new Promise((resolve, reject) => {
  //     dfInst?.validate((error: any) => {
  //       if (error) return reject(error)
  //       resolve(true)
  //     })
  //   })
  //   // new Promise((resolve, reject) => {
  //   //   baseFormRef.value?.validate((error) => {
  //   //     if (error) return reject(error)
  //   //     resolve(true)
  //   //   })
  //   // })
  // ])
  const pass = await submitR()
  if (!pass) {
    canReview.value = false
    return
  }
  // if (!formInst.value) return
  // await formInst.value.validate()

  if (!noBack) loadingReview.value = true
  else loading.value = true
  const regEx = /^03\d{14}$/
  if (formData.value.BMTRA039 && !regEx.test(formData.value.BMTRA039)) {
    loading.value = false
    loadingReview.value = false
    canReview.value = false
    return message.error('馆藏码为03开头的16位数字，请修改！')
  }
  for (let i = 0; i < formData.value.ZM?.length; i++) {
    const item = formData.value.ZM[i]
    if (!regEx.test(item.BMLSWX054)) {
      loading.value = false
      loadingReview.value = false
      canReview.value = false
      return message.error('子目馆藏码为03开头的16位数字，请修改！')
    }
  }
  // type.value 1 是编目保存，2是添加保存
  const [error, res] = await sendRequest({
    module: 'collectProcess',
    api: type.value == 1 || type.value == 3 ? 'saveCatalogInfoUpdate' : 'addCatalogInfoUpdate',
    override: {
      data: {
        catalogInfo: {
          contentJson: JSON.stringify(formData.value),
          subItemCode: route.query?.subItemCode
        },
        collectingDistrictDataList: formatedDataUtil.collectingDistrictDataList(formData.value),
        collectingResponsibleDataList: formatedDataUtil.collectingResponsibleDataList(
          formData.value
        ),
        // itemsStaging: {
        //   itemName: form.itemName,
        //   assetCode: form.assetCode,
        //   serialNumber: form.serialNumber,
        //   shelfNumber: form.shelfNumber,
        //   itemSetId: form.choice,
        //   subItemCode: route.query?.subItemCode,
        //   isbn:formData?.value?.['BMTS02']
        // },
        fileIds: form.fileIds,
        collectId: route.query?.id,
        batchCode: route.query?.type == 2 ? route.query.batchCode : null //添加才有批次code
        // ...form.itemsStaging
      }
    }
  })
  loading.value = false
  loadingReview.value = false
  canReview.value = true
  if (error) {
    canReview.value = false
    return message.error(error.message) // 接口报错
  }
  if (res.code !== 0) {
    canReview.value = false // 馆藏码重复等报错
    return message.error(res.msg)
  }
  if (!noBack && route.query?.type != 2) return //审核先保存但是页面不提示和返回
  if (route.query?.type == 2) {
    //添加和编目公用页面,添加完成之后需要关闭页签
    routeReplace()
    reviewSubItemCode.value = res.data
  }
  message.success(res.msg)
  window.flags.flushMakeMenuCollectList = true
  routeReplace()
}
const reviewSubItemCode = ref() // 添加保存并提交审核工单号
const submitAndReview = async () => {
  await submit(false)
  if (canReview.value) {
    const [error, res] = await sendRequest({
      module: 'collectProcess',
      api: 'batchReviewUpdate',
      override: {
        data: {
          // subItemCodes: [route?.query?.subItemCode]
          subItemCodes: type.value == 2 ? [reviewSubItemCode.value] : [route?.query?.subItemCode]
        }
      }
    })
    if (error) return message.error(error.message)
    if (res.code == 500) message.error(res.msg)
    else {
      message.success(res.msg)
      loadingReview.value = false
      window.flags.flushMakeMenuCollectList = true
      goBack()
    }
  }
}

const handleUpdateFormData = (key: string, value: unknown) => {
  formData.value[key] = value
}
const inputGroupName = (v: string) => {
  form.GroupName = v.trim()
}
//
const makeLineDetail = async (e: any) => {
  const [error, res] = await sendRequest({
    module: 'collectProcess',
    api: 'getListByItemSetId',
    uri: {
      // @ts-ignore
      itemSetId: e,
      // @ts-ignore
      subItemCode: route.query?.subItemCode
    }
  })
  if (error) return
  if (res.code !== 0) return

  GroupList.value = res.data
}

const handleUpdateCompony = (v: any) => {
  form.compony = v
  formSearchRef.value?.restoreValidation()
  numberRule.value = {
    yesNO: {
      required: form.compony == 2 || form.compony == 0 ? false : true,
      trigger: ['blur', 'input'],
      validator: () => /^[0-9-.]+$/.test(form.yesNO),
      message: '只允许数字和字符-'
    }
  }
  form.yesNO = null
}
</script>

<style lang="scss" scoped>
.included-modal {
  width: 1600px;
  height: 640px;
  .included-container {
    position: relative;
    padding: 0 0;
    align-items: flex-start;
    display: flex;
    overflow: hidden;
  }
  .menuStyle {
    display: flex;
    padding: 10px;
    height: calc(100% - 56px);
    .dynamic-form-demo {
      padding: 30px 45px 10px;
      // height:300px;
    }

    .table {
      height: 100%;
      // padding: 29px 30px 42px;
    }

    .topTitle {
      font-size: 22px;
      font-family: PingFangSC, PingFang SC;
      font-weight: 500;
      color: #5fb17f;
      margin-bottom: 10rem;
    }

    .inputWH {
      width: 300rem;
    }

    .inputGroup {
      width: 140rem;
    }

    .ac-card {
      // padding: 20rem;
      background-color: #e1e1e1;
    }

    .ac-title {
      font-size: 22px;
      font-family: PingFangSC, PingFang SC;
      font-weight: 500;
      color: #5fb17f;
      margin-bottom: 10rem;
    }
  }
  .container-bottom {
    position: absolute;
    bottom: 0;
    display: flex;
    width: 100%;
    height: 56px;
    padding: 0px 24px;
    justify-content: center;
    align-items: center;
    gap: 24px;
    border-top: 1px solid #e2e2e2;
    .btn-list {
      display: flex;
      gap: 24px;
    }
  }
}
:deep(.n-form-item-feedback-wrapper) {
  min-height: 20px;
}
:deep(.n-form-item-label__text) {
  color: #4e5969;
  text-align: right;
  font-size: 12px;
  line-height: 22px; /* 183.333% */
}
:deep(.n-form-item-blank) {
  width: 168px;
}
</style>
